package com.wswy.wzcx.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArraySet;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.blankj.utilcode.util.SizeUtils;
import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.recycler.Component;
import com.che.libcommon.recycler.OnItemClickedListener;
import com.che.libcommon.recycler.RowFactory;
import com.che.libcommon.recycler.RowListAdapter2;
import com.che.libcommon.ui.BaseFragment;
import com.che.libcommon.ui.VOMessage;
import com.che.libcommon.ui.loading.ILoadingView;
import com.che.libcommon.ui.loading.LoadingDelegate;
import com.che.libcommon.ui.loading.OnLoadingShowCallback;
import com.che.libcommon.utils.CollectionUtils;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.TrafficViolationInfo;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.model.wzdb.WzdbCreateResp;
import com.wswy.wzcx.module.InternalMsgCodeKt;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.Constants;
import com.wswy.wzcx.ui.activity.ModuleActivity;
import com.wswy.wzcx.ui.adapter.WZDBChooseAdapter;
import com.wswy.wzcx.ui.component.WZDBChooseComponent;
import com.wswy.wzcx.ui.data.WZDBMode;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.ui.other.CloseDelegate;
import com.wswy.wzcx.ui.other.DialogFactory;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.other.ViewHelp;
import com.wswy.wzcx.ui.wzdb.WZDBSubmitCertActivity;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wangduheng26 on 2018/3/22.
 * wangduheng26@gmail.com
 */

@Deprecated
public class WZDBChooseFragment extends BaseFragment {
    public static final String TAG = "WZDBChooseFragment";
    TextView textView;
    RecyclerView recyclerView;

    UserCarInfo mode=null;

    List<WZDBMode> list;
    RowListAdapter2<WZDBMode> adapter2;
    private ArraySet<WZDBMode> set;

    private boolean requesting = false;

    private TrafficViolationInfo defaultChoose;

    public static WZDBChooseFragment newInstance(Bundle bundle){
        WZDBChooseFragment fragment = new WZDBChooseFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

//    public static WZDBChooseFragment newInstance(UserCarInfo mode,TrafficViolationInfo defaultChoose) {
//
//        Bundle args = new Bundle();
//
//
//        args.putParcelable(Constants.EXTRA_DATA, mode);
//        args.putParcelable("defaultChoose",defaultChoose);
//        WZDBChooseFragment fragment = new WZDBChooseFragment();
//        fragment.setArguments(args);
//        return fragment;
//    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey(Constants.EXTRA_DATA)){
            mode = arguments.getParcelable(Constants.EXTRA_DATA);
            defaultChoose = arguments.getParcelable("defaultChoose");
        }

    }

    LoadingDelegate loadingDelegate;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Context context = getContext();
        assert context != null;
        RelativeLayout layout = new RelativeLayout(context);
        //layout.setBackgroundColor(ContextCompat.getColor(context,R.color.default_background_color));
        RelativeLayout.LayoutParams params = LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, 50);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        textView = new TextView(context);
        textView.setId(ViewHelp.generateViewId());
        textView.setMinHeight(AndroidUtilities.dp(50));
        textView.setBackgroundResource(R.drawable.common_btn_background);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
        textView.setTextColor(Color.WHITE);
        textView.setGravity(Gravity.CENTER);
        textView.setText(R.string.next_step);
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startSubmit();
            }
        });
        LayoutHelper.setSelectable(textView);
        layout.addView(textView, params);
        recyclerView = new RecyclerView(context);
        recyclerView.setHasFixedSize(true);
        DividerItemDecoration decoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        decoration.setDrawable(ContextCompat.getDrawable(context, R.drawable.list_divider_h));
        recyclerView.addItemDecoration(decoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        params = LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT);
        params.addRule(RelativeLayout.ABOVE, textView.getId());
        layout.addView(recyclerView, params);


        FrameLayout root = new FrameLayout(context);
        root.addView(layout,LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,LayoutHelper.MATCH_PARENT));
        loadingDelegate = new LoadingDelegate(root, layout, new ILoadingView.LoadingConfigure() {
            @Override
            public VOMessage getEmptyMessage() {
                return VOMessage.createEmpty(0, 0, 0, 0);
            }

            @Override
            public View.OnClickListener getOnEmptyClickClickListener() {
                return null;
            }

            @Override
            public View.OnClickListener getOnRetryClickListener() {
                return new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setupPage();
                    }
                };
            }

            @Override
            public OnLoadingShowCallback getOnLoadingShowCallback() {
                return null;
            }
        });



        //联系客服悬浮按钮
        ImageView imageView = new ImageView(getContext());
        imageView.setImageResource(R.drawable.float_wechatservice);

        FrameLayout.LayoutParams lp = new LayoutParams(SizeUtils.dp2px(60),SizeUtils.dp2px(60));
        lp.gravity = Gravity.RIGHT|Gravity.BOTTOM;

        lp.bottomMargin = SizeUtils.dp2px(128);

        root.addView(imageView,lp);

        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showTelHelp(v.getContext(),getString(R.string.wzdb_tel));
            }
        });

        return root;
    }

    private void startSubmit() {
        if (set == null || set.isEmpty() || requesting){
            return;
        }

        //下一步 提交

        ArrayList<WZDBMode> modes = new ArrayList<>(set);

        requesting = true;
        createOrder(modes);

        StatTools.sendClick(getContext(), StatisticsId.clickWZDB_NextStep);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        delegate = new CloseDelegate(this,InternalMsgCodeKt.UPLOAD_COMPLETE_WDZD);

        setupPage();
    }

    private void setupPage() {
        Api.get().fetchWZDBData(mode)
                .subscribe(new ApiOptionalResultObserver<List<WZDBMode>>(){

                    @Override
                    protected void onApiResult(@Nullable List<WZDBMode> list) {
                        showList(list);
                        loadingDelegate.showData();
                    }

                    @Override
                    protected void onApiError(@Nullable BaseResult result) {
                        toastErrorMsg(result);
                        loadingDelegate.showError(result);
                    }

                    @Override
                    protected void onStart() {
                        super.onStart();
                        loadingDelegate.showLoading(true);
                    }
                });
    }

    CloseDelegate delegate;

    private void showList(List<WZDBMode> data) {
        if (data == null || data.isEmpty()) {
            recyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showText("没有查到违章信息");
                    finish();
                }
            }, 100);
            return;
        }

//        RowFactory<WZDBMode> factory = parent -> {
//            WZDBChooseComponent component = new WZDBChooseComponent(parent);
////            component.setBoxClickListener((v, info) -> {
////                handleClick(info);
////            });
//            return component;
//        };
        list = new ArrayList<>();
        list.addAll(data);

        set = new ArraySet<>(list.size());

        if (defaultChoose != null){
            //默认选中
            int idx = 0;
            boolean founded = false;
            for (WZDBMode wzdbMode : list) {
                if (TextUtils.equals(wzdbMode.getUniquerMd5Id(),defaultChoose.uniqueMd5Id)){
                    founded = true;
                    break;
                }
                idx++;
            }

            if (founded){

                WZDBMode wzdbMode = list.get(idx);
                list.remove(idx);
                list.add(0,wzdbMode);

                set.add(wzdbMode);
            }

        }


        adapter2 = new WZDBChooseAdapter(set, new RowFactory<WZDBMode>() {
            @Override
            public Component<WZDBMode> create(ViewGroup parent) {
                return new WZDBChooseComponent(parent);
            }
        });
        adapter2.setOnItemClickedListener(new OnItemClickedListener<WZDBMode>() {
            @Override
            public void onItemClicked(View view, WZDBMode wzdbMode, int position) {
                handleClick(wzdbMode, position);
            }
        });

        recyclerView.setAdapter(adapter2);

        adapter2.setItems(list);

        adapter2.notifyDataSetChanged();
        changeBtnStatus();
    }

    private void handleClick(WZDBMode info, int position) {
        if (!info.checkDJ()) {
            return;
        }
        boolean selected = set.contains(info);
        if (selected) {
            set.remove(info);
        }else {
            set.add(info);
        }


//        v.setSelected(!selected);
        adapter2.notifyItemChanged(position);
        changeBtnStatus();
    }

    private void changeBtnStatus() {
        if (set != null && !set.isEmpty()) {

            int countPoint = 0;
            for (WZDBMode wzdbMode : set) {
                if (wzdbMode != null && wzdbMode.getDeductPoint() != null){
                    countPoint+=wzdbMode.getDeductPoint();
                }
                if (countPoint > 10){
                    ToastUtils.showText("扣分过多，无法处理。");
                    break;
                }
            }


            textView.setEnabled(countPoint < 10);

            //textView.setEnabled(true);
        } else {
            textView.setEnabled(false);
        }
    }

    @Override
    public void onDestroy() {
        if (delegate != null)
            delegate.onDestroy();
        super.onDestroy();
    }

    @Override
    public String getFragmentTitle() {
        return "选择代办条目";
    }



    private void createOrder(ArrayList<WZDBMode> modes){
        //生成订单
        requesting = true;

        StringBuilder submitStr = new StringBuilder();
        for (WZDBMode mode : modes) {
            submitStr.append(mode.getUniquerMd5Id()).append(",");
        }
        if (submitStr.length() > 0)
            submitStr.deleteCharAt(submitStr.length() - 1);

        final String ids = submitStr.toString();

        Api.get().submitWZDBList(ids).subscribe(new ApiOptionalResultObserver<WzdbCreateResp>(){

            @Override
            protected void onApiResult(@Nullable WzdbCreateResp resp) {
                requesting = false;
                if (resp != null){

                    if(CollectionUtils.isEmpty(resp.getList())){
                        //不需要提供资料，直接支付
                        Intent targetIntent = ModuleActivity.getTargetIntent(getContext(), WZDBSubmitFragment.TAG);
                        targetIntent.putExtra("orderInfo", resp.getOrderInfo());
                        startActivity(targetIntent);


                    } else {
                        //需要提供资料，跳转到提交代办资料页面

                        WZDBSubmitCertActivity.Companion.start(getContext(),ids,resp.getList(),mode);

                    }

                }
            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                requesting = false;
                toastErrorMsg(result);
            }
        });

    }
}
